<?php

/**
 *    用户中心
 *
 *    @author   yanghj 2014.5.26
 *    @usage    none
 */
class MemberApp extends MemberbaseApp
{
	var $_feed_enabled = false;
	var $_week = array(1=>'周一',2=>'周二',3=>'周三',4=>'周四',5=>'周五',6=>'周六',7=>'周日');
	var $_member_from;
	var $_goods_mod;
	function __construct()
	{
		$this->MemberApp();
	}
	function MemberApp()
	{
		parent::__construct();
		$ms =& ms();
		$this->_feed_enabled = $ms->feed->feed_enabled();
		$this->_member_from = isset($_GET['from']) ? trim($_GET['from']) : 'buyer';
		$this->assign('member_from', $this->_member_from);
		$this->assign('feed_enabled', $this->_feed_enabled);
		$this->_goods_mod =& m('goods');
	}
	function index()
	{

		/* 清除新短消息缓存 */
		$cache_server =& cache_server();
		$cache_server->delete('new_pm_of_user_' . $this->visitor->get('user_id'));

		$user = $this->visitor->get();
		$user_mod =& m('member');
		$goods_mod = &m('goods');
		$info = $user_mod->get_info($user['user_id']);
		$user['portrait'] = portrait($user['user_id'], $info['portrait'], 'middle');

		//用户可用余额
		$usermoney_mod =& m('usermoney');
		$usermoney_info = $usermoney_mod->get("user_id = {$user['user_id']}");
		$user['user_money']  =  empty($usermoney_info['user_money'])?0:$usermoney_info['user_money'];
		//
		$this->assign('user', $user);

		/* 店铺信用和好评率 */
		if ($user['has_store'])
		{
			/*$store_mod =& m('store');
			$store = $store_mod->get_info($user['has_store']);
			$step = intval(Conf::get('upgrade_required'));
			$step < 1 && $step = 5;
			$store['credit_image'] = $this->_view->res_base . '/images/' . $store_mod->compute_credit($store['credit_value'], $step);
			$this->assign('store', $store);
			$this->assign('store_closed', STORE_CLOSED);*/
		}
		$goodsqa_mod = & m('goodsqa');
		$groupbuy_mod = & m('groupbuy');
		/* 买家提醒：待付款、待确认、待评价订单数 */
		$order_mod =& m('order');
        $sql = "SELECT 
                count(case when status = '" . ORDER_PENDING . "' then order_id end) submitted,
                count(case when status = '" . ORDER_SHIPPED . "' then order_id end) shipped,
                count(case when status = '" . ORDER_ACCEPTED . "' then order_id end) accepted,
                count(case when status = '" . ORDER_FINISHED . "' AND evaluation_status = 0 then order_id end) evalua
                FROM {$order_mod->table} where buyer_id = '{$user['user_id']}'";
        $buyer_stat = $order_mod->getRow($sql);
		$this->assign('buyer_stat', $buyer_stat);

		/* 卖家提醒：待处理订单和待发货订单 */
		if ($user['has_store'])
		{

			/*$sql7 = "SELECT COUNT(*) FROM {$order_mod->table} WHERE seller_id = '{$user['user_id']}' AND status = '" . ORDER_PENDING . "'";
			$sql8 = "SELECT COUNT(*) FROM {$order_mod->table} WHERE seller_id = '{$user['user_id']}' AND status = '" . ORDER_ACCEPTED . "'";
			$sql9 = "SELECT COUNT(*) FROM {$goodsqa_mod->table} WHERE store_id = '{$user['user_id']}' AND reply_content ='' ";
			$sql10 = "SELECT COUNT(*) FROM {$groupbuy_mod->table} WHERE store_id='{$user['user_id']}' AND state = " .GROUP_END;
			$seller_stat = array(
			'submitted' => $order_mod->getOne($sql7),
			'accepted'  => $order_mod->getOne($sql8),
			'replied'   => $goodsqa_mod->getOne($sql9),
			'groupbuy_end'   => $goodsqa_mod->getOne($sql10),
			);
			$this->assign('seller_stat', $seller_stat);*/
		}
		/* 卖家提醒： 店铺等级、有效期、商品数、空间 */
		if ($user['has_store'])
		{
			/*$store_mod =& m('store');
			$store = $store_mod->get_info($user['has_store']);

			$grade_mod = & m('sgrade');
			$grade = $grade_mod->get_info($store['sgrade']);


			$goods_num = $goods_mod->get_count_of_store($user['has_store']);
			$uploadedfile_mod = &m('uploadedfile');
			$space_num = $uploadedfile_mod->get_file_size($user['has_store']);
			$sgrade = array(
			'grade_name' => $grade['grade_name'],
			'add_time' => empty($store['end_time']) ? 0 : sprintf('%.2f', ($store['end_time'] - gmtime())/86400),
			'goods' => array(
			'used' => $goods_num,
			'total' => $grade['goods_limit']),
			'space' => array(
			'used' => sprintf("%.2f", floatval($space_num)/(1024 * 1024)),
			'total' => $grade['space_limit']),
			);
			$this->assign('sgrade', $sgrade);*/

		}

		/* 待审核提醒 */
		if ($user['state'] != '' && $user['state'] == STORE_APPLYING)
		{
			$this->assign('applying', 1);
		}
		/* 收藏商品 */
		$collect_goods = $goods_mod->find(array(
		'join'  => 'be_collect,has_default_spec',
		'fields'=> 'this.goods_id,this.goods_name,this.if_show,this.default_image,collect.add_time,this.price,goodsspec.spec_id,goodsspec.stock',
		'conditions' => 'collect.user_id = ' . $this->visitor->get('user_id'),
		'count' => true,
		'order' => 'collect.add_time DESC',
		'limit' => 4,
		));
		foreach ($collect_goods as $key => $goods)
		{
			empty($goods['default_image']) && $collect_goods[$key]['default_image'] = Conf::get('default_goods_image');
		}
		$collect_goods_count = $goods_mod->getCount();   //收藏商品总数

		/* 当前位置 */
		$this->_curlocal(LANG::get('member_center'),    url('app=member'),
		LANG::get('overview'));

		/* 当前用户中心菜单 */
		$this->_curitem('overview');
		$this->_config_seo('title', Lang::get('member_center'));
		$this->assign('security_data', $this->account_security_level());
		$this->assign('collect_goods', $collect_goods);
		$this->assign('collect_goods_count', $collect_goods_count);
		$this->assign('safety_level', array('1' => '低','2' => '中','3' => '高'));
		$this->assign('date',date('m-d'));
		$this->assign('week',$this->_week[date('N')]);
		/* 获取订单列表 */
		$page = $this->_get_page(6);
		$model_order =& m('order');
		!$_GET['type'] && $_GET['type'] = 'all_orders';
		$con = array(
		array(      //按订单状态搜索
		'field' => 'status',
		'name'  => 'type',
		'handler' => 'order_status_translator',
		),
		array(      //按店铺名称搜索
		'field' => 'seller_name',
		'equal' => 'LIKE',
		),
		array(      //按下单时间搜索,起始时间
		'field' => 'add_time',
		'name'  => 'add_time_from',
		'equal' => '>=',
		'handler'=> 'gmstr2time',
		),
		array(      //按下单时间搜索,结束时间
		'field' => 'add_time',
		'name'  => 'add_time_to',
		'equal' => '<=',
		'handler'=> 'gmstr2time_end',
		),
		array(      //按订单号
		'field' => 'order_sn',
		),
		);
		$conditions = $this->_get_query_conditions($con);
		/* 查找订单 */
		$orders = $model_order->findAll(array(
		'conditions'    => "buyer_id=" . $this->visitor->get('user_id') . "{$conditions}",
		'fields'        => 'this.*',
		'count'         => true,
		'limit'         => $page['limit'],
		'order'         => 'add_time DESC',
		'include'       =>  array(
		'has_ordergoods',       //取出商品
		),
		));
		foreach ($orders as $key1 => $order)
		{
			foreach ($order['order_goods'] as $key2 => $goods)
			{
				empty($goods['goods_image']) && $orders[$key1]['order_goods'][$key2]['goods_image'] = Conf::get('default_goods_image');
			}
		}

		$page['item_count'] = $model_order->getCount();
		$this->assign('types', array('all'     => Lang::get('all_orders'),
		'pending' => Lang::get('pending_orders'),
		'submitted' => Lang::get('submitted_orders'),
		'accepted' => Lang::get('accepted_orders'),
		'shipped' => Lang::get('shipped_orders'),
		'finished' => Lang::get('finished_orders'),
		'canceled' => Lang::get('canceled_orders')));
		$this->assign('type', $_GET['type']);
		$member_mod =& m('member');
		foreach($orders as $k => $v){
			$ak = array_keys($v['order_goods']);
			$orders[$k]['index'] = $ak[0];
			$orders[$k]['count'] = count($v['order_goods']);
			foreach($v['order_goods'] as $val){
				$orders[$k]['quantity'] += $val['quantity'];
			}
			$orders[$k]['endtime'] = date('m/d/Y H:s:m',$v['add_time']+604800);
			$orders[$k]['member_info'] = $member_mod->get_info($v['seller_id']);
		}
		//var_dump($this->_get_goods_history());
		/* 浏览历史 */
		$this->assign('goods_history', $this->_get_goods_history());
		$this->assign('orders', $orders);
		$this->_format_page($page);
		$this->assign('page_info', $page);
		$this->display('member.index.html');
	}

	/**
     *    注册一个新用户
     *
     *    @author    yanghj 2014.5.26
     *    @return    void
     */
	function register()
	{
		if($_GET['mode'] == 'succeed')
		{
            $ret_url = !empty($_GET['ret_url'])?trim($_GET['ret_url']):SITE_URL;
			$this->assign('app_img', 'registertt.jpg');
            $this->assign('ret_url', $ret_url);
			$this->display('member.register.succeed.html');
			return;

		}
		if ($this->visitor->has_login)
		{
			header("Location:index.php?app=member");
			return;
		}
		if (!IS_POST)
		{
			if (!empty($_GET['ret_url']))
			{
				$ret_url = trim($_GET['ret_url']);
			}
			else
			{
				if (isset($_SERVER['HTTP_REFERER']))
				{
					$ret_url = $_SERVER['HTTP_REFERER'];
				}
				else
				{
					$ret_url = SITE_URL . '/index.php';
				}
			}
			$this->assign('ret_url', rawurlencode($ret_url));
			$this->assign('app_img', 'registertt.jpg');
			$this->_curlocal(LANG::get('user_register'));
			$this->_config_seo('title', Lang::get('user_register') . ' - ' . Lang::get('site_title'));

			if (Conf::get('captcha_status.register'))
			{
				$this->assign('captcha', 1);
			}

			/* 导入jQuery的表单验证插件 */
			$this->import_resource('jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js,user.validate.js');
			$this->display('member.register.html');
		}
		else
		{
			if (!$_POST['agree'])
			{
				$this->show_warning('agree_first');

				return;
			}
			//检查图片验证码
			if($_POST['captcha'])
			{
				if (Conf::get('captcha_status.register') && base64_decode($_SESSION['captcha']) != strtolower($_POST['captcha']))
				{
					$this->show_warning('captcha_failed');
					return;
				}

			}

			if ($_POST['password'] != $_POST['password_confirm'])
			{
				/* 两次输入的密码不一致 */
				$this->show_warning('inconsistent_password');
				return;
			}

			/* 注册并登陆 */
			$user_name = trim($_POST['user_name']);
			$password  = $_POST['password'];
			$passlen = strlen($password);
            $ret_url = !empty($_POST['ret_url'])?trim($_POST['ret_url']):SITE_URL;
			$email = $user_name;
			$mobile_code = trim($_POST['mobile_verification_code']);
            $password_level     = (int)($_POST['password_level'])<1 ? 1 :(int)($_POST['password_level']);
			//检查手机验证码
			if($mobile_code)
			{
                                if(!isset($_SESSION['start_sent_time']) || time() - $_SESSION['start_sent_time'] > 1800)
                                {
                                    $this->show_warning("手机验证码已无效请重新发送!");
                                    return;
                                }
                                if ($user_name != $_SESSION['mobile'])
                                {
                                    $this->show_warning("手机号码不正确!");
                                    return false;
                                }
				if($mobile_code != $_SESSION['mobile_code'])
				{
					$this->show_warning("手机验证码错误!");
					return;
				}

			}
			if (!is_account($user_name))
			{
				$this->show_warning('账户名不正确');

				return;
			}
			if ($passlen < 6 || $passlen > 20)
			{
				$this->show_warning('password_length_error');

				return;
			}

			$ms =& ms(); //连接用户中心
			$user_id = $ms->user->register($user_name, $password, $email, array('password_level'=>$password_level));

			if (!$user_id)
			{
				$this->show_warning($ms->user->get_error());

				return;
			}
			$this->_hook('after_register', array('user_id' => $user_id));
			//登录
			$this->_do_login($user_id);

			/* 同步登陆外部系统 */
			$synlogin = $ms->user->synlogin($user_id);

			$account_type = check_account_type($user_name);
			//如果是邮箱用户则同时绑定邮箱
			if($account_type == 1)
			{
				$user_safety_mod = & m('usersafety');
				$user_safety_mod->add_edit(array('binding_email' => $user_name,'user_id' => $user_id), $user_id);
				if ($user_safety_mod->has_error())
				{
					$this->show_warning($user_safety_mod->get_error());
					return;
				}

			}
			//如果是手机用户则同时绑定手机
			if($account_type == 2)
			{
				$user_safety_mod = & m('usersafety');
				$user_safety_mod->add_edit(array('binding_mobile' => $user_name,'user_id' => $user_id), $user_id);
				if ($user_safety_mod->has_error())
				{
					$this->show_warning($user_safety_mod->get_error());
					return;
				}

			}

			#TODO 可能还会发送欢迎邮件

			header("Location:index.php?app=member&act=register&mode=succeed&ret_url=$ret_url");
			return;
		}
	}


	/**
     *    检查用户是否存在
     *
     *    @author    Garbin
     *    @return    void
     */
	function check_user()
	{
		$user_name = empty($_GET['user_name']) ? null : trim($_GET['user_name']);
		if (!$user_name)
		{
			echo ecm_json_encode(false);

			return;
		}
		$ms =& ms();

		echo ecm_json_encode($ms->user->check_username($user_name));
	}

	/**
     *    修改基本信息
     *
     *    @author    Hyber
     *    @usage    none
     */
	function profile(){
		$user_id = $this->visitor->get('user_id');

		if (!IS_POST)
		{
			/* 当前位置 */

			if($this->_member_from == 'seller')
			{
				$this->_curlocal(LANG::get('seller_center'),  'index.php?app=seller',
				LANG::get('my_account'),  'index.php?app=account_security&from=seller',
				LANG::get('my_information'));
				$this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('my_profile'));
			}
			else
			{
				$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
				LANG::get('my_account'),  'index.php?app=account_security&from=buyer',
				LANG::get('my_information'));
				$this->_config_seo('title', Lang::get('buyer_center') . ' - ' . Lang::get('my_profile'));
			}

			/* 当前用户中心菜单 */
			$this->_curitem('my_profile');

			/* 当前所处子菜单 */
			$this->_curmenu('profile_list');

			$ms =& ms();    //连接用户系统
			$edit_avatar = $ms->user->set_avatar($this->visitor->get('user_id')); //获取头像设置方式

			$model_user =& m('member');
			$profile    = $model_user->get_info(intval($user_id));
			$profile['portrait'] = portrait($profile['user_id'], $profile['portrait'], 'middle');
			$this->assign('profile',$profile);
			$this->import_resource(array(
			'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js,mlselection.js,ajaxupload.js',
			));
			$this->_get_regions();
			$this->assign('edit_avatar', $edit_avatar);
			$this->display('member.profile.html');
		}
		else
		{
			$data = array(
			'real_name' => html_script(trim($_POST['real_name'])),
			'gender'    => (int)$_POST['gender'],
			'region_id'     => (int)$_POST['region_id'],
			'region_name'   => html_script(trim($_POST['region_name'])),
			'im_qq'   => trim($_POST['im_qq']),
			'phone_tel'   => trim($_POST['phone_tel']),
			'phone_mob'   => trim($_POST['phone_mob']),
			);           
			if (!empty($_POST['portrait']))
			{
				$portrait = $this->upload_copy_img($_POST['portrait']);
				if ($portrait === false)
				{
					return;
				}
				$data['portrait'] = $portrait;
			}

			$model_user =& m('member');
			$model_user->edit($user_id , $data);
			if ($model_user->has_error())
			{
				$this->show_warning($model_user->get_error());

				return;
			}

			$this->show_message('edit_profile_successed');
		}
	}
	/**
     *    修改密码
     *
     *    @author    yanghj
     *    @usage    none
     */
	function password(){

		$user_id = $this->visitor->get('user_id');
		if (!IS_POST)
		{
			/* 当前位置 */

			if($this->_member_from == 'seller')
			{
				$this->_curlocal(LANG::get('seller_center'),  'index.php?app=seller',
				LANG::get('my_account'),  'index.php?app=account_security&from=seller',
				LANG::get('my_information'));
				$this->_config_seo('title', Lang::get('seller_center') . ' - ' . Lang::get('edit_password'));
			}
			else
			{
				$this->_curlocal(LANG::get('member_center'), 'index.php?app=member',
				LANG::get('my_account'),  'index.php?app=account_security&from=buyer',
				LANG::get('my_information'));
				$this->_config_seo('title', Lang::get('buyer_center') . ' - ' . Lang::get('edit_password'));
			}


			/* 当前用户中心菜单 */
			$this->_curitem('my_safety');

			/* 当前所处子菜单 */
			$this->_curmenu('edit_password');
			$this->import_resource(array(
			'script' => 'jquery.plugins/jquery.validate.js,jquery.plugins/additional-methods.js,user.validate.js',
			));
			$this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('edit_password'));
			$this->display('member.password.html');
		}
		else
		{
			/* 两次密码输入必须相同 */
			$orig_password      = trim($_POST['orig_password']);
			$new_password       = trim($_POST['new_password']);
			$confirm_password   = trim($_POST['confirm_password']);
			$password_level     = (int)($_POST['password_level'])<1 ? 1 :(int)($_POST['password_level']);
			if ($new_password != $confirm_password)
			{
				$this->show_warning('twice_pass_not_match');

				return;
			}
			if (!$new_password)
			{
				$this->show_warning('no_new_pass');

				return;
			}
			$passlen = strlen($new_password);
			if ($passlen < 6 || $passlen > 20)
			{
				$this->show_warning('password_length_error');

				return;
			}

			/* 修改密码 */
			$ms =& ms();    //连接用户系统
			$result = $ms->user->edit($this->visitor->get('user_id'), $orig_password, array(
			'password'  => $new_password, 'password_level' => $password_level
			));
			if (!$result)
			{
				/* 修改不成功，显示原因 */
				$this->show_warning($ms->user->get_error());

				return;
			}

			$this->show_message('edit_password_successed');
		}
	}
	/**
     *    修改电子邮箱
     *
     *    @author    Hyber
     *    @usage    none
     */
	function email(){
		$user_id = $this->visitor->get('user_id');
		if (!IS_POST)
		{
			/* 当前位置 */
			$this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
			LANG::get('edit_email'));

			/* 当前用户中心菜单 */
			$this->_curitem('my_profile');

			/* 当前所处子菜单 */
			$this->_curmenu('edit_email');
			$this->import_resource(array(
			'script' => 'jquery.plugins/jquery.validate.js',
			));
			$this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('edit_email'));
			$this->display('member.email.html');
		}
		else
		{
			$orig_password  = $_POST['orig_password'];
			$email          = isset($_POST['email']) ? trim($_POST['email']) : '';
			if (!$email)
			{
				$this->show_warning('email_required');

				return;
			}
			if (!is_email($email))
			{
				$this->show_warning('email_error');

				return;
			}

			$ms =& ms();    //连接用户系统
			$result = $ms->user->edit($this->visitor->get('user_id'), $orig_password, array(
			'email' => $email
			));
			if (!$result)
			{
				$this->show_warning($ms->user->get_error());

				return;
			}

			$this->show_message('edit_email_successed');
		}
	}

	/**
     * Feed设置
     *
     * @author Garbin
     * @param
     * @return void
     **/
	function feed_settings()
	{
		if (!$this->_feed_enabled)
		{
			$this->show_warning('feed_disabled');
			return;
		}
		if (!IS_POST)
		{
			/* 当前位置 */
			$this->_curlocal(LANG::get('member_center'),  'index.php?app=member',
			LANG::get('feed_settings'));

			/* 当前用户中心菜单 */
			$this->_curitem('my_profile');

			/* 当前所处子菜单 */
			$this->_curmenu('feed_settings');
			$this->_config_seo('title', Lang::get('user_center') . ' - ' . Lang::get('feed_settings'));

			$user_feed_config = $this->visitor->get('feed_config');
			$default_feed_config = Conf::get('default_feed_config');
			$feed_config = !$user_feed_config ? $default_feed_config : unserialize($user_feed_config);

			$buyer_feed_items = array(
			'store_created' => Lang::get('feed_store_created.name'),
			'order_created' => Lang::get('feed_order_created.name'),
			'goods_collected' => Lang::get('feed_goods_collected.name'),
			'store_collected' => Lang::get('feed_store_collected.name'),
			'goods_evaluated' => Lang::get('feed_goods_evaluated.name'),
			'groupbuy_joined' => Lang::get('feed_groupbuy_joined.name')
			);
			$seller_feed_items = array(
			'goods_created' => Lang::get('feed_goods_created.name'),
			'groupbuy_created' => Lang::get('feed_groupbuy_created.name'),
			);
			$feed_items = $buyer_feed_items;
			if ($this->visitor->get('manage_store'))
			{
				$feed_items = array_merge($feed_items, $seller_feed_items);
			}
			$this->assign('feed_items', $feed_items);
			$this->assign('feed_config', $feed_config);
			$this->display('member.feed_settings.html');
		}
		else
		{
			$feed_settings = serialize($_POST['feed_config']);
			$m_member = &m('member');
			$m_member->edit($this->visitor->get('user_id'), array(
			'feed_config' => $feed_settings,
			));
			$this->show_message('feed_settings_successfully');
		}
	}

	/**
     *    三级菜单
     *
     *    @author    Hyber
     *    @return    void
     */
	function _get_member_submenu()
	{
		$submenus =  array(
		array(
		'name'  => 'basic_information',
		'url'   => 'index.php?app=member&amp;act=profile',
		),
		array(
		'name'  => 'edit_password',
		'url'   => 'index.php?app=member&amp;act=password',
		),
		array(
		'name'  => 'edit_email',
		'url'   => 'index.php?app=member&amp;act=email',
		),
		);
		if ($this->_feed_enabled)
		{
			$submenus[] = array(
			'name'  => 'feed_settings',
			'url'   => 'index.php?app=member&amp;act=feed_settings',
			);
		}

		return $submenus;
	}

	/**
     * 上传头像
     *
     * @param int $user_id
     * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
     */
	function _upload_portrait($user_id)
	{
		$file = $_FILES['portrait'];
		if ($file['error'] != UPLOAD_ERR_OK)
		{
			return '';
		}
		import('uploader.lib');
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE);
		$uploader->addFile($file);
		if ($uploader->file_info() === false)
		{
			$this->show_warning($uploader->get_error(), 'go_back', 'index.php?app=member&amp;act=profile');
			return false;
		}
		$uploader->root_dir(ROOT_PATH);
		return $uploader->save('data/files/mall/portrait/' . ceil($user_id / 500), $user_id);
	}
    
    /**
     * 复制ajax上传的图片
     *
     * @param string $src
     * @return mix false表示复制失败,string表示复制文件地址
     */
	function upload_copy_img($src)
	{
		if (!file_exists($src))
		{
			return false;
		}
        import('uploader.lib');
		$uploader = new Uploader();
        $arr = pathinfo($src);
        $extension = $arr['extension'];
        $target = 'data/files/mall/portrait/' . ceil($this->visitor->get('user_id') / 500).'/'.$this->visitor->get('user_id').'.'.$extension;
        $file_url = $uploader->copy_uploaded_file($src, $target);
        unlink($src);
        return $file_url;

	}
    
    /**
     * 上传图片
     *
     * @return mix false表示上传失败,空串表示没有上传,string表示上传文件地址
     */
	function ajax_uploadify()
	{
	    $rs = array('state'=>false, 'msg'=>'');
		$file = $_FILES['Filedata'];
		if ($file['error'] != UPLOAD_ERR_OK)
		{
		    $rs['msg'] = '请选择上传的图片';
            echo ecm_json_encode($rs);
			return;
		}
		import('uploader.lib');
		$uploader = new Uploader();
		$uploader->allowed_type(IMAGE_FILE_TYPE);
        $uploader->allowed_size(512000);
		$uploader->addFile($file);
		if ($uploader->file_info() === false)
		{
			$rs['msg'] = '图片的格式不对或者大小超过了500kb';
            echo ecm_json_encode($rs);
			return;
		}
		$uploader->root_dir(ROOT_PATH);
        $file_dir = 'data/files/tmp/'.date('Y-m-d');
        $file_url = $uploader->save($file_dir, $uploader->random_filename());
        if(file_exists(ROOT_PATH.'/'.$file_url))
        {
             $rs['state'] = true;
             $rs['msg'] = $file_url;
             echo ecm_json_encode($rs);
			return;          
        }
        else
        {
             $rs['msg'] = '上传失败';
             echo ecm_json_encode($rs);
			return; 
        }
	}
    

	/**
     * ajax检查旧密码是否正确
     *
     */
	function ajaxCheckPassword()
	{
		$old_password = trim($_POST['orig_password']);
		$user_mod =& m('member');
		$password = $user_mod->getOne("SELECT password FROM {$user_mod->table} WHERE user_id = " .$this->visitor->get('user_id'));
		if($password != md5($old_password))
		{
			echo ecm_json_encode(false);
			return;

		}
		echo ecm_json_encode(true);
	}

	/**
     *账号安全等级
     */
	function account_security_level()
	{
		$user_safety_mod =& m('usersafety');
		$i = 0;
		$rs = array();
		$accout_security = $user_safety_mod->get(array('conditions'    => 'user_id = ' . $this->visitor->get('user_id')));
		if($accout_security['pay_password']){$i++;}
		if($accout_security['binding_email']){$i++;}
		if($accout_security['binding_mobile']){$i++;}
		if($i==0){$i=1;}
		$rs['level'] = $i;
		$rs['security'] = $accout_security;
		return $rs;

	}
	/* 取得浏览历史 */
	function _get_goods_history()
	{
		$goods_list = array();
		$goods_ids  = ecm_getcookie('goodsBrowseHistory');
		$goods_ids  = $goods_ids ? explode(',', $goods_ids) : array();
		if ($goods_ids)
		{
			$rows = $this->_goods_mod->find(array(
			'conditions' => $goods_ids,
			'fields'     => 'goods_name,default_image,price',
			));
			foreach ($goods_ids as $goods_id)
			{
				if (isset($rows[$goods_id]))
				{
					empty($rows[$goods_id]['default_image']) && $rows[$goods_id]['default_image'] = Conf::get('default_goods_image');
					$goods_list[] = $rows[$goods_id];
				}
			}
            krsort($goods_list);
		}
		return $goods_list;
	}

	/**
     *    获取区域信息
     *
     */
	function _get_regions()
	{
		$model_region =& m('region');
		$regions = $model_region->get_list(0);
		if ($regions)
		{
			$tmp  = array();
			foreach ($regions as $key => $value)
			{
				$tmp[$key] = $value['region_name'];
			}
			$regions = $tmp;
		}
		$this->assign('regions', $regions);
	}

}

?>
